package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;


    /**
     * 上传图片(文件)
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result uploadImg(MultipartFile file){

        //1、修改图片名字
        //1.1、原始文件名
        String originalFilename = file.getOriginalFilename();
        //1.2、截取文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //1.3、构造新文件名称
        String name = UUID.randomUUID().toString() + extension;


        //2、调用工具类，上传图片，并把返回值返回给上一层
        try {
            return Result.success(aliOssUtil.upload(file.getBytes(), name));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传文件失败...");
        }
    }
}
